/*
* Licensed under the MIT License
* 
* Copyright (c) 2010 Kay Kreuning
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* 
* http://code.google.com/p/as3hyvesapi
*/
package nl.hyves.api.oauth
{
	import com.adobe.crypto.HMAC;
	import com.adobe.crypto.SHA1;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLRequest;
	
	import nl.hyves.api.utils.Base64;
	
	[Event(name="complete", type="flash.events.Event")]
	
	public class OAuth extends EventDispatcher implements IOAuth
	{
		private const HTTP_METHOD:String				= "GET";
		private const SIGNATURE_METHOD_HMAC_SHA1:String	= "HMAC-SHA1";
		
		private var consumerKey:String;
		private var consumerSecret:String;
		
		private var _platformParameters:Object;
		private var _isAuthorized:Boolean = false;
		private var token:OAuthToken;
		private var _endpoint:String;
		
		public function get platformParameters():Object
		{
			return _platformParameters;
		}
		
		public function set platformParameters(value:Object):void
		{
			_platformParameters = value;
		}
		
		public function get isAuthorized():Boolean
		{
			return _isAuthorized;
		}
		
		public function get userId():String
		{
			return (token && token.userId) ? token.userId : null;
		}
		
		public function get methods():Array
		{
			return (token && token.methods) ? token.methods : null;
		}
		
		public function get expireDate():Date
		{
			return (token && token.expireDate) ? token.expireDate : null;
		}
		
		public function get endpoint():String
		{
			return _endpoint;
		}
		
		public function set endpoint(value:String):void
		{
			_endpoint = value;
		}
		
		public function OAuth(consumerKey:String, consumerSecret:String, endpoint:String, platformParameters:Object = null)
		{
			this.consumerKey = consumerKey;
			this.consumerSecret = consumerSecret;
			_endpoint = endpoint;
			this.platformParameters = platformParameters;
		}
		
		public function getURLRequest(parameters:Object):URLRequest
		{
			parameters = mergeParameters(parameters, platformParameters);
			
			if (token) parameters["oauth_token"]	= token.token;
			parameters["oauth_nonce"]				= int(Math.random() * 0x7FFFFFFF).toString();
			parameters["oauth_timestamp"]			= int(new Date().getTime() / 1000 + 0.5).toString();
			parameters["oauth_consumer_key"]		= consumerKey;
			parameters["oauth_signature_method"]	= SIGNATURE_METHOD_HMAC_SHA1;
			parameters["oauth_signature"]			= calculateSignature(endpoint, parameters);
			
			
			return new URLRequest(endpoint + "?" + decode(parameters));
		}
		
		public function updateCredentials(token:OAuthToken):void
		{
			this.token = token;
			
			if (token.userId && token.methods && token.expireDate)
			{
				_isAuthorized = true;
				
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		
		public function getCredentials():OAuthToken
		{
			return token;
		}
		
		public function authorize(authorizer:IAuthorizer):void
		{
			authorizer.authorize(this);
		}
		
		private function calculateSignature(url:String, parameters:Object):String
		{
			var string:String = encodeURIComponent(HTTP_METHOD) + "&" +
				encodeURIComponent(url) + "&" + 
				encodeURIComponent(decode(parameters));
			
			var hash:String = HMAC.hash(
				encodeURIComponent(consumerSecret) + "&" + encodeURIComponent(token ? token.secret || "" : ""),
				string,
				SHA1);
			
			return Base64.encodeBigEndian(hash);
		}
		
		private function decode(parameters:Object):String
		{
			var array:Array = new Array();
			
			for (var key:String in parameters)
			{
				array.push(key + "=" + encodeURIComponent(parameters[key].toString()));
			}
			
			array.sort();
			
			return array.join("&");
		}
		
		private function mergeParameters(obj1:Object, obj2:Object):Object
		{
			var object:Object = new Object();
			
			for (var key:String in obj1)
				object[key] = obj1[key];
			
			for (key in obj2)
				object[key] = obj2[key];
			
			return object;
		}
	}
}